package services;

import assemblers.interfaces.AddressAssembler;
import assemblers.interfaces.AddressInfoAssembler;
import handlers.PersonServiceHandler;
import infos.AddressInfo;
import model.Address;
import model.Person;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;

@Path("address")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Stateless
public class AddressService {
    private PersonServiceHandler personServiceHandler;
    private AddressAssembler addressAssembler;
    private AddressInfoAssembler addressInfoAssembler;

    @EJB
    public void setPersonServiceHandler(PersonServiceHandler personServiceHandler) {
        this.personServiceHandler = personServiceHandler;
    }

    @EJB
    public void setAddressAssembler(AddressAssembler addressAssembler) {
        this.addressAssembler = addressAssembler;
    }

    @EJB
    public void setAddressInfoAssembler(AddressInfoAssembler addressInfoAssembler) {
        this.addressInfoAssembler = addressInfoAssembler;
    }

    @Path("find")
    @POST
    public List<AddressInfo> getAddress(AddressInfo addressInfo) {
        List<Address> addresses =  personServiceHandler.findAddressByInfo(addressAssembler.assemble(addressInfo));
        return addressInfoAssembler.assembleList(addresses);
    }

    @Path("{personId}")
    @PUT
    public AddressInfo addAddress(@PathParam("personId") Long personId, AddressInfo addressInfo) {
        Address address = addressAssembler.assemble(addressInfo);
        address = personServiceHandler.addAddress(address);
        Person person = personServiceHandler.findPerson(personId);
        personServiceHandler.linkAddress(person, address);
        return addressInfoAssembler.assemble(address);
    }

    @Path("{personId}/{addressId}")
    @DELETE
    public Response detachAddress(@PathParam("personId") Long personId,
                                  @PathParam("addressId") Long addressId) {
        Person person = personServiceHandler.findPerson(personId);
        Address address = personServiceHandler.findAddress(addressId);
        personServiceHandler.detachAddress(person, address);
        return Response.ok().build();
    }

}
